package com.sunvua.water_mark

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Build
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import top.zibin.luban.InputStreamProvider
import top.zibin.luban.Luban
import java.io.File

/** WaterMarkPlugin */
class WaterMarkPlugin: FlutterPlugin, Pigeon.BookApi,WaterMark.WaterMarkApi,
    WaterMarkFilePath.WaterMarkFilePathApi {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel : MethodChannel
    private lateinit var  context: Context;
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
//    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "water_mark")
//    channel.setMethodCallHandler(this)

        context = flutterPluginBinding.applicationContext

        // setup
        Pigeon.BookApi.setup(flutterPluginBinding.binaryMessenger, this)
        WaterMark.WaterMarkApi.setup(flutterPluginBinding.binaryMessenger, this)
        WaterMarkFilePath.WaterMarkFilePathApi.setup(flutterPluginBinding.binaryMessenger, this)

    }

//  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
////    call.arguments<>()
//    if (call.method == "getPlatformVersion") {
////      ImageUtil.addTextWatermark()
//     val argList :String = call.arguments as String;
////      println(argList)
//      result.success("Android ${android.os.Build.VERSION.RELEASE}")
//    } else {
//      result.notImplemented()
//    }
//  }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        Pigeon.BookApi.setup(binding.binaryMessenger,null);
        WaterMark.WaterMarkApi.setup(binding.binaryMessenger,null);
    }

    override fun search(keyword: String?): MutableList<Pigeon.Book> {
        println("Android:$keyword,curr:${System.currentTimeMillis()}")
        var cc = mutableListOf<Pigeon.Book>()
        var book = Pigeon.Book();
        book.author="??"
        book.title="title"
        cc.add(book)
        return  cc
    }


    override fun fileToWaterMark(request: WaterMark.WaterMarkFileRequest?): WaterMark.WaterMarkFileReply {
        var waterMarkFileReply = WaterMark.WaterMarkFileReply();
        request?.run {
            var bitmap =ImageUtil.BytesToBitmap(request.backgroundfile)
            if (bitmap != null) {

//          var textList= mutableListOf<String>("时间：2021-10-29 09:09:09","地点：唐山","人员：asd","???")
                var textList= request.textContext.split(Regex("\n"))
                var waterMarkerBitmap= JaveImageUtil.addTextWatermark(bitmap,textList,request.fontSize.toInt(), Color.argb(90,255,255,255),40f,bitmap.height-(textList.size*request.fontSize).toFloat(),false)

                if (waterMarkerBitmap != null) {
                    var path = context.externalCacheDir!!.absolutePath;
                    var beforeFile = File("$path/${System.currentTimeMillis()}.png")

                    var file = Luban.with(context).load("").ignoreBy(500).get()

//            Luban.with().load(list).get();

                    waterMarkFileReply.waterMarkfile=ImageUtil.BitmapToBytes(waterMarkerBitmap)
                };

            };
        }
        return  waterMarkFileReply
//    return WaterMark.WaterMarkFileReply()
    }

    override fun fileToWaterMark(request: WaterMarkFilePath.WaterMarkFilePathRequest?): WaterMarkFilePath.WaterMarkFilePathReply {

        var waterMarkFileReply =WaterMarkFilePath.WaterMarkFilePathReply();
        request?.let {
            var startcurr = System.currentTimeMillis();
//            var file = Luban.with(context).load(request.backgroundfilePath).ignoreBy(500).get()[0]
            var file = File(request.backgroundfilePath);
            var filebytes = file.readBytes();
            var bitmap =ImageUtil.BytesToBitmap(filebytes)
            println("转换bitmap用时：${System.currentTimeMillis()-startcurr}")
            if (bitmap != null) {

                var textList= request.textContext.split(Regex("\n"))
                var waterMarkerBitmap= JaveImageUtil.addTextWatermark(bitmap,textList,bitmap.width/60, Color.argb(90,255,255,255),40f,bitmap.height-(textList.size*(bitmap.width/60)).toFloat(),false)
                println("bitmap合并用时：${System.currentTimeMillis()-startcurr}")
                println("bitmap合并后大小：${waterMarkerBitmap.byteCount}")
                if (waterMarkerBitmap != null) {

                    val fos = file.outputStream();

                    waterMarkerBitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
                    fos.flush()
                    fos.close()
                    println("bitmap转成图片用时：${System.currentTimeMillis()-startcurr}")
                    var file = Luban.with(context).load(file.absolutePath).ignoreBy(500).get()[0]
                    waterMarkFileReply.waterMarkfilePath =file.absolutePath
                    println("用时：${System.currentTimeMillis()-startcurr}")
                };

            };
        }
        return waterMarkFileReply;
    }
}
